import React, { Component } from 'react';
import PropTypes from 'prop-types';

import styles from './style.scss';
import { noop } from '@utils';
import Tooltips from '@components/Tooltips';

export default class MenuItem extends Component {

    static propTypes = {
        menuKey: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
        parentMenu: PropTypes.object,
        rootMenu: PropTypes.object,
        children: PropTypes.any,
        title: PropTypes.node,
        level: PropTypes.number,
        isActive: PropTypes.bool,
        isDisabled: PropTypes.string,
        isCollapsed: PropTypes.bool,
        onItemHover: PropTypes.func,
        onSelect: PropTypes.func,
        onClick: PropTypes.func,
        onDestory: PropTypes.func,
    };

    static defaultProps = {
        level: 1,
        onSelect: noop,
        onItemHover: noop,
        onDestory: noop,
        onClick: noop,
    };

    static isMenuItem = true;

    onMouseEnter = evt => {
        const { menuKey, onItemHover } = this.props;
        onItemHover({
            menuKey: String(menuKey),
            isHover: true,
            event: evt
        });
    };

    onMouseLeave = evt => {
        const { menuKey, onItemHover } = this.props;
        onItemHover({
            menuKey: String(menuKey),
            isHover: false,
            event: evt
        });
    };

    onClick = evt => {
        const { menuKey, onClick, onSelect, isActive } = this.props;
        const info = {
            menuKey: String(menuKey),
            item: this,
            event: evt,
        };
        onClick(info);
        if (!isActive) {
            onSelect(info);
        }
    };

    render() {
        const props = this.props;
        const style = { ...props.style };
        const attrs = {
            role: 'menu-item',
            onClick: props.isDisabled ? null : this.onClick,
            onMouseEnter: props.isDisabled ? null : this.onMouseEnter,
            onMouseLeave: props.isDisabled ? null : this.onMouseLeave,
        };
        let arrCls = [styles.menuItem];
        if (props.className) {
            arrCls.push(props.className);
        }
        if (props.isActive) {
            arrCls.push('active');
        }
        if (props.isDisabled) {
            arrCls.push('disabled');
        }
        attrs.className = arrCls.join(' ');
        style.paddingLeft = style.paddingLeft || parseInt(this.props.level, 10) * 20 + 'px';

        return (
            <Tooltips title={props.isCollapsed ? props.title : ''} placement="right">
                <li {...attrs} style={style} > {props.children} </li>
            </Tooltips>
        );
    }
}
